﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Xml;

using System.Data;
using System.Data.Common;
using System.Web.Security;

using TractRecord.Authenticated;

namespace TractRecord.Code
{
    public class ProjectsSiteMapProvider : StaticSiteMapProvider 
    {
        private String _siteMapFileName;
        private SiteMapNode _rootNode = null;
        private const String SiteMapNodeName = "siteMapNode";

        private bool _temp = false;

        public override SiteMapNode RootNode
        {
            get 
            {
                return BuildSiteMap();
            }
        }

        public override void Initialize(string name, NameValueCollection attributes)
        {
            base.Initialize(name, attributes);
            _siteMapFileName = attributes["siteMapFile"];
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            return RootNode;
        }

        protected override void Clear()
        {
            lock (this)
            {
                _rootNode = null;
                base.Clear();
            }
        }

        public override SiteMapNode BuildSiteMap()
        {
            lock (this)
            {

                if (_rootNode == null && Membership.GetUser() != null)
                {
                    Clear();

                    string url = "/Authenticated/Projects.aspx";
                    string title = "Projects";
                    string description = "All active projects";

                    _rootNode = new SiteMapNode(this,
                        (url + title).GetHashCode().ToString(), url, title, description);

                    AddNode(_rootNode);

                    
                    //DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_ProjectSummaryForUser_Get");
                    //cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", Membership.GetUser().ProviderUserKey.ToString()));
                    //cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ActiveInd", true));

                    //IDataReader r = Code.DataAccess.Data.ExecuteReader(cmd);

                    //while (r.Read())
                    //{
                    //    //AddDynamicChildElement(projects, "/Authenticated/Project.aspx?id=" + r["ProjectId"].ToString(), r["Name"].ToString(), r["Description"].ToString());
                    //}

                    // Load the sitemap's xml from the file.
                    //XmlDocument siteMapXml = LoadSiteMapXml();
                    // Create the first site map item from the top node in the xml.
                    //XmlElement rootElement =
                    //    (XmlElement)siteMapXml.GetElementsByTagName(
                    //    SiteMapNodeName)[0];

                    // This is the key method - add the dynamic nodes to the xml
                    //AddDynamicNodes(rootElement);
                    //AddActiveProjectNodes(rootElement);
                    // Now build up the site map structure from the xml
                    //GenerateSiteMapNodes(rootElement);
                }
            }
            return _rootNode;
        }
        
        private void AddActiveProjectNodes(XmlElement rootElement)
        {
            try
            {
                if (Roles.IsUserInRole("Project Administrator"))
                {
                    //SiteMapNode parent = base.FindSiteMapNode("/Authenticated/Default.aspx");

                    //SiteMapNode projects = AddDynamicChildElement(parent, "/Authenticated/Projects.aspx", "Projects", "All project settings.");

                    XmlElement projects = AddDynamicChildElement(rootElement, "", "Football Teams", "List of football teams created dynamically");

                    DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_ProjectSummaryForUser_Get");
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", Membership.GetUser().ProviderUserKey.ToString()));
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ActiveInd", true));

                    IDataReader r = Code.DataAccess.Data.ExecuteReader(cmd);

                    while (r.Read())
                    {
                        AddDynamicChildElement(projects, "/Authenticated/Project.aspx?id=" + r["ProjectId"].ToString(), r["Name"].ToString(), r["Description"].ToString());

                    }
                }
            }
            catch (NullReferenceException)
            { }
            catch { throw; }
        }


        private static XmlElement AddDynamicChildElement(XmlElement parentElement, String url, String title, String description)
        {
            // Create new element from the parameters
            XmlElement childElement = parentElement.OwnerDocument.CreateElement(SiteMapNodeName);
            childElement.SetAttribute("url", url);
            childElement.SetAttribute("title", title);
            childElement.SetAttribute("description", description);

            // Add it to the parent
            parentElement.AppendChild(childElement);
            return childElement;
        }

        private void GenerateSiteMapNodes(XmlElement rootElement)
        {
            _rootNode = GetSiteMapNodeFromElement(rootElement);
            AddNode(_rootNode);
            CreateChildNodes(rootElement, _rootNode);
        }

        private void CreateChildNodes(XmlElement parentElement, SiteMapNode parentNode)
        {
            foreach (XmlNode xmlElement in parentElement.ChildNodes)
            {
                if (xmlElement.Name == SiteMapNodeName)
                {
                    SiteMapNode childNode = GetSiteMapNodeFromElement((XmlElement)xmlElement);
                    AddNode(childNode, parentNode);
                    CreateChildNodes((XmlElement)xmlElement, childNode);
                }
            }
        }

        private SiteMapNode GetSiteMapNodeFromElement(XmlElement rootElement)
        {
            SiteMapNode newSiteMapNode;
            String url = rootElement.GetAttribute("url");
            String title = rootElement.GetAttribute("title");
            String description = rootElement.GetAttribute("description");

            // The key needs to be unique, so hash the url and title.
            newSiteMapNode = new SiteMapNode(this,
                (url + title).GetHashCode().ToString(), url, title, description);

            return newSiteMapNode;
        }
    }
}